package com.ooqiu.gaming.api.base;

import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.Map;

/**
 * @author Eenie
 * @date 2017/11/21
 */

public class BaseRequest {
    private boolean needLogin;
    private boolean forceLogin;
    private JSONObject body;
    private String token;

    public BaseRequest() {

    }

    public BaseRequest(Object body) {
        this.body = JSON.parseObject(JSON.toJSONString(body));
    }

    public boolean isNeedLogin() {
        return needLogin;
    }


    public boolean isForceLogin() {
        return forceLogin;
    }


    public void setNeedLogin(boolean needLogin) {
        this.needLogin = needLogin;
    }

    public void setForceLogin(boolean forceLogin) {
        this.forceLogin = forceLogin;
    }

    public BaseRequest setLoginState(boolean need, boolean force) {
        setForceLogin(force);
        setNeedLogin(need);
        return this;
    }

    public Object getBody() {
        return body;
    }

    public BaseRequest setBody(Object body) {
        this.body = JSON.parseObject(JSON.toJSONString(body));
        return this;
    }


    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }


    public String getBodyStr() {
        if (!TextUtils.isEmpty(token)) {
            body.put("token", token);
            return mapToStr(body);
        } else {
            return mapToStr(body);
        }
    }


    private String mapToStr(JSONObject body) {
        Map<String, String> params = body.toJavaObject(Map.class);
        StringBuilder sb = new StringBuilder();
        for (String key : params.keySet()) {
            sb.append(String.format("%s=%s&", key, params.get(key)));
        }
        if (sb.length() > 0) {
            return sb.subSequence(0, sb.length() - 1).toString();
        }
        return "";
    }

}
